use chrono::{prelude::Utc, DateTime, Datelike, Duration, Local, NaiveDate, NaiveDateTime};
use regex::Regex;

use crate::utils::string_util::chinese_to_number;

pub fn get_now_time_ymd() -> String {
    //获取当前时间
    let now = Utc::now();
    let (_is_common_era, year) = now.year_ce();
    year.to_string() + now.month().to_string().as_str() + now.day().to_string().as_str()
}

pub fn get_now_time_y_m_d() -> (u32, u32, u32) {
    //获取当前时间
    let now = Utc::now();
    let (_is_common_era, year) = now.year_ce();
    (year, now.month(), now.day())
}

pub fn get_now_time_m() -> i64 {
    //获取当前时间
    let now = Utc::now();
    now.timestamp()
}

pub fn get_ymd_by_y_m_d(y: u32, m: u32, d: u32) -> String {
    y.to_string() + "年" + m.to_string().as_str() + "月" + d.to_string().as_str() + "日"
}

pub fn get_ymd_num_by_y_m_d(y: u32, m: u32, d: u32) -> i32 {
    let mut num = y.to_string();
    if m < 10 {
        num.push_str("0");
    }
    num.push_str(m.to_string().as_str());
    if d < 10 {
        num.push_str("0");
    }
    num.push_str(d.to_string().as_str());
    let num: i32 = num.parse().unwrap();
    num
}

pub fn get_ymd_m_by_str(time: String) -> i64 {
    let date = DateTime::parse_from_str(&(time + " 00:00:01 +0000"), "%Y年%m月%d日 %H:%M:%S %z");
    match date {
        Ok(date) => {
            return date.timestamp();
        }
        Err(e) => {
            log::info!("{}", e);
            return 0;
        }
    }
}

pub fn get_ymd_str_by_m(time: i64) -> String {
    let datetime = DateTime::<Utc>::from_timestamp(time, 0).unwrap();

    datetime.format("%Y-%m-%d").to_string()
}

pub fn get_ym_str() -> String {
    let now = Utc::now();
    now.format("%Y%m").to_string()
}

pub fn extract_time_from_string(input: &str) -> Vec<String> {
    // 更新后的正则表达式，支持几乎所有常见的时间格式
    let time_pattern = r"(?x)
        (\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})|
        (\d{4}-\d{2}-\d{2}\s\d{2}:\d{2})|
        (\d{4}年\d{2}月\d{2}日\s\d{2}:\d{2}(:\d{2})?) |
        (\d{4}-\d{2}-\d{2}) |
        (\d{4}年\d{2}月\d{2}日) |
        (\d{2}:\d{2}(:\d{2})?) |
        (\d{2}点\d{2}分(\d{2}秒)?) |
        (\d{4}/\d{2}/\d{2}) |
        (\d{2}/\d{2}/\d{4}) |
        (\d{8}) |
        (\d{4}年\d{2}月\d{2}日\s\d{2}:\d{2}:\d{2})|
        (\d{4}年\d{2}月\d{2}日\s\d{2}:\d{2})|
        (\d{4}年\d{2}月\d{2}日)|
        (\d{4}年\d{2}月)|
        (\d{2}:\d{2}:\d{2})|
        (\d{2}:\d{2})|
        (\d{2}点\d{2}分(\d{2}秒)?)|
        (\d{2}:\d{2}\s(AM|PM))|
        (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}(Z|[+-]\d{2}:\d{2}))|
        (\d{4}年\d{2}月\d{2}日\s(上午|下午)\d{2}:\d{2})|
        (\d{10}) |
        (今天|昨天|明天) |
        ([一二三四五六七八九十百千两半几\d]+(秒|分钟|分|小时|天|日|周|个月|月|年))
    ";
    let re = Regex::new(time_pattern).unwrap();

    // 查找所有匹配的时间
    re.find_iter(input)
        .map(|mat| mat.as_str().to_string())
        .collect()
}

pub fn parse_time_string(time_str: &str) -> Option<NaiveDateTime> {
    if let Ok(date_time) = NaiveDateTime::parse_from_str(time_str, "%Y-%m-%d %H:%M:%S") {
        return Some(date_time);
    }
    if let Ok(date_time) = NaiveDateTime::parse_from_str(time_str, "%Y-%m-%d %H:%M") {
        return Some(date_time);
    }
    if let Ok(date) = NaiveDate::parse_from_str(time_str, "%Y-%m-%d") {
        return Some(NaiveDateTime::new(
            date,
            chrono::NaiveTime::from_hms_opt(0, 0, 0).unwrap(),
        ));
    }
    if let Ok(date) = NaiveDate::parse_from_str(time_str, "%Y年%m月%d日") {
        return Some(NaiveDateTime::new(
            date,
            chrono::NaiveTime::from_hms_opt(0, 0, 0).unwrap(),
        ));
    }
    if let Ok(date_time) = NaiveDateTime::parse_from_str(time_str, "%Y/%m/%d") {
        return Some(date_time);
    }
    if let Ok(date_time) = NaiveDateTime::parse_from_str(time_str, "%d/%m/%Y") {
        return Some(date_time);
    }
    // 5. 相对时间：今天、昨天、明天
    match time_str {
        "今天" => return Some(Local::now().naive_local().date().and_hms_opt(0, 0, 0)?),
        "昨天" => {
            return Some(
                (Local::now().naive_local().date() - Duration::days(1)).and_hms_opt(0, 0, 0)?,
            );
        }
        "明天" => {
            return Some(
                (Local::now().naive_local().date() + Duration::days(1)).and_hms_opt(0, 0, 0)?,
            );
        }
        _ => {}
    }

    // 6. 中文相对时间如 "2天", "三周", "半个月"
    let re = Regex::new(
        r"(?P<num>[一二三四五六七八九十百千两半\d]+)(?P<unit>秒|分钟|分|小时|天|日|周|个月|月|年)",
    )
    .unwrap();
    if let Some(caps) = re.captures(time_str) {
        let num_str = &caps["num"];
        let unit = &caps["unit"];
        let num = chinese_to_number(num_str)?;
        let delta = match unit {
            "秒" => Duration::seconds(num),
            "分" | "分钟" => Duration::minutes(num),
            "小时" => Duration::hours(num),
            "天" | "日" => Duration::days(num),
            "周" => Duration::weeks(num),
            "月" => Duration::days(30 * num),
            "个月" => Duration::days(30 * num),
            "年" => Duration::days(365 * num),
            _ => return None,
        };
        return Some((Local::now().naive_local().date() + delta).and_hms_opt(0, 0, 0)?);
    }

    // 对于其他格式可以继续添加更多的解析
    None
}
